﻿using System.Text;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using AhCha.Fortunate.ModelsDto.MySQL.WeChatDto;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Authorization;
using AhCha.Fortunate.Common.Const;

namespace AhCha.Fortunate.Api.Controllers.Public
{
    /// <summary>
    /// 微信 - 用户订阅通知后，微信推送相关数据
    /// </summary>
    [AllowAnonymous]
    [ApiExplorerSettings(GroupName = SwaggerGroupName.PublicModules)]
    public class WeChatController : BaseApiController
    {
        //微信文档
        //https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/subscribe-message.html

        /// <summary>
        /// 微信验证（确认是否是微信调用）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<string> WeChatSubscribeMessageVerify([FromQuery] WeChatSubscribeMessageVerify input)
        {
            //自定义的token，如需修改，请在微信公众号中同步修改
            string _token = "";
            var sortedParams = new[] { _token, input.Timestamp, input.Nonce }.OrderBy(p => p).ToArray();
            var concatenatedParams = string.Join("", sortedParams);
            using (var sha1 = SHA1.Create())
            {
                var hashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(concatenatedParams));
                var calculatedSignature = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
                if (calculatedSignature == input.Signature)
                {
                    return input.Echostr;
                }
                else
                {
                    return "";
                }
            }
        }

        /// <summary>
        /// 用户订阅后，微信回调
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> WeChatSubscribeMessageCallback([FromBody] WeChatSubscribeMessageCallback input)
        {

            List<WeChatPush> WeChatPushs = new List<WeChatPush>();
            if (input.List.Type == JTokenType.Object)
            {
                WeChatPushs.Add(input.List.ToObject<WeChatPush>());
            }
            else if (input.List.Type == JTokenType.Array)
            {
                JArray listArray = (JArray)input.List;
                foreach (var item in listArray)
                {
                    WeChatPushs.Add(item.ToObject<WeChatPush>());
                }
            }
            //存储数据库
            return "Success";
        }
    }
}
